package cn.liziguo.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @author Liziguo
 * @date 2021/12/19 23:32
 */
public final class Captcha {

    public final String id;

    public final String code;

    public final BufferedImage image;

    public Captcha(String id, String code, BufferedImage image) {
        this.id = id;
        this.code = code;
        this.image = image;
    }

    /**
     * @return 获取小写验证码
     */
    public String getLowerCode() {
        return code.toLowerCase();
    }

    /**
     * @return 大写验证码
     */
    public String getUpperCode() {
        return code.toUpperCase();
    }

    /**
     * 把图片转换成字节数组
     *
     * @return
     */
    public byte[] toBytes() {
        try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", out);
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成图片的base64编码
     *
     * @return
     */
    public String toBase64Code() {
        return Base64.getEncoder().encodeToString(toBytes());
    }

}
